import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';

// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 根据环境加载配置
const env = process.env.NODE_ENV || 'development';
const envPath = path.resolve(__dirname, `../../.env.${env}`);

// 尝试加载环境变量
try {
  const result = dotenv.config({ path: envPath });
  
  if (result.error) {
    console.error('JWT Utils - Error loading environment variables:', result.error.message);
  }
} catch (error) {
  console.error('JWT Utils - Failed to load environment variables:', error);
}

const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET) {
  console.error('JWT Utils - JWT_SECRET is not defined in environment variables');
  console.error(`JWT Utils - Env file path: ${envPath}`);
  console.error(`JWT Utils - Env file exists: ${fs.existsSync(envPath)}`);
  throw new Error('JWT_SECRET must be defined in environment variables');
}

const JWT_EXPIRES_IN = '7d'; // Token 有效期为7天

/**
 * 生成 JWT token
 * @param {Object} payload - Token 载荷
 * @returns {string} JWT token
 */
export function generateToken(payload) {
  if (!JWT_SECRET) {
    throw new Error('JWT_SECRET is not available');
  }
  return jwt.sign(payload, JWT_SECRET, {
    expiresIn: JWT_EXPIRES_IN
  });
}

/**
 * 验证 JWT token
 * @param {string} token - JWT token
 * @returns {Object|null} 解码后的载荷或null
 */
export function verifyToken(token) {
  if (!JWT_SECRET) {
    console.error('JWT Utils - JWT_SECRET is not available during token verification');
    return null;
  }
  try {
    return jwt.verify(token, JWT_SECRET);
  } catch (error) {
    console.error('JWT Utils - Token verification failed:', error.message);
    return null;
  }
}

/**
 * 从请求头中获取 token
 * @param {Object} ctx - Koa 上下文
 * @returns {string|null} token 或 null
 */
export function getTokenFromHeader(ctx) {
  const authorization = ctx.headers.authorization;
  if (!authorization) {
    return null;
  }

  const parts = authorization.split(' ');
  if (parts.length !== 2 || parts[0] !== 'Bearer') {
    return null;
  }

  return parts[1];
}
